<?php
/*
 * @Author: an
 * @Date: 2021/12/6
 * @Description: 腾讯身份识别
 */


namespace App\Services\Tencent\identify;


use App\Services\Tencent\BaseService;

class IdCard extends BaseService
{
    /**
     * OCR-身份证识别
     * @param $imgUrl 身份证图片路径
     * @param $cardType 0身份证正面（头像） 1身份证反面（国徽）
     * @return bool|mixed|string
     * @throws \Exception
     * @author an
     * @time 2021-12-06 14:45
     */
    public function check($imgUrl = null, $cardType = 0)
    {
        $token = $this->getToken();
        $headers = [
            'Authorization:' . $token,
            'Content-Type:application/json'
        ];
        $body = [
            'appid' => $this->appid,
            'bucket' => 'tencentyun',
            'card_type' => $cardType,
            'url_list' => [
                $imgUrl
            ]
        ];
        $url = 'https://recognition.image.myqcloud.com/ocr/idcard';
        $data = $this->request($url, json_encode($body), $headers);
        $data = json_decode($data, true);
        return $data;
    }

    /**
     * 拼接签名串
     * 拼接多次有效签名串：
     * a=[appid]&b=[bucket]&k=[SecretID]&e=[expiredTime]&t=[currentTime]&r=[rand]&f=[fileid]
     * 拼接单次有效签名串：
     * a=[appid]&b=[bucket]&k=[SecretID]&e=[expiredTime]&t=[currentTime]&r=[rand]&f=[fileid]
     * 注意：
     * 多次有效签名串中 fileid 为可选参数。
     * fileid 为空，表示不绑定资源，例如上传签名和下载签名。
     * fileid 不为空，表示绑定资源，例如绑定资源的下载。
     * @param $expired 过期时间，秒
     * @return string
     * @author an
     * @time 2021-12-06 14:16
     */
    protected function getToken($expired = null)
    {
        $appid = $this->appid;
        $bucket = $this->bucket;
        $secret_id = $this->secretId;
        $secret_key = $this->secretKey;
        if(!$expired){
            $expired = time() + 2592000;//一个月
        }
        $onceExpired = 0;
        $current = time();
        $rdm = rand();
        $fileid = "tencentyunSignTest";
        $srcStr = 'a=' . $appid . '&b=' . $bucket . '&k=' . $secret_id . '&e=' . $expired . '&t=' . $current . '&r=' . $rdm . '&f=';
//        $srcWithFile = 'a=' . $appid . '&b=' . $bucket . '&k=' . $secret_id . '&e=' . $expired . '&t=' . $current . '&r=' . $rdm . '&f=' . $fileid;
//        $srcStrOnce = 'a=' . $appid . '&b=' . $bucket . '&k=' . $secret_id . '&e=' . $onceExpired . '&t=' . $current . '&r=' . $rdm
//            . '&f=' . $fileid;
        $signStr = base64_encode(hash_hmac('SHA1', $srcStr, $secret_key, true) . $srcStr);
//        $srcWithFile = base64_encode(hash_hmac('SHA1', $srcWithFile, $secret_key, true) . $srcWithFile);
//        $signStrOnce = base64_encode(hash_hmac('SHA1', $srcStrOnce, $secret_key, true) . $srcStrOnce);
        return $signStr;
    }
}
